import asyncio
import json
import signal
import logging

from sdv.vdb.subscriptions import DataPointReply
from sdv_model import vehicle1, vehicle2
from sdv.vehicle_app import VehicleApp

logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)

class SampleApp(VehicleApp):
    """
    Sample skeleton vehicle app.

    The skeleton subscribes to a getSpeed MQTT topic
    to listen for incoming requests to get
    the current vehicle speed and publishes it to
    a response topic.

    It also subcribes to the VehicleDataBroker
    directly for updates of the
    Vehicle.Speed signal and publishes this
    information via another specific MQTT topic
    """

    def __init__(self, vehicle_client: vehicle1):
        super().__init__()
        self.Vehicle = vehicle_client
        self._idx = 0 

    async def on_start(self):
        self.Vehicle.Speed.subscribe(self.on_speed_change)
        logger.debug("On start ...")
        print("Mock up for mqtt")
        await self.publish_mqtt_event("sampleapp/bt_cmd/reponse", json.dumps({"3d_model_door": "open"}),)
        print("Mock up for VSS")
        #await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.set(90)
        asyncio.create_task(self.on_timer())

    async def on_timer(self):
        logger.debug("TASK LOOP ...")
        logger.debug("task loopping ...")
        await self.publish_mqtt_event("sampleapp/tasks", json.dumps({"period tasks": self._idx}),)
        self._idx = self._idx + 1
        #await asyncio.sleep(2.0)
        await self.Vehicle.Body.Lights.Running.IsOn.set(True)
        await asyncio.sleep(2.0)
        await self.Vehicle.Body.Lights.Brake.IsActive.set(True)
        await asyncio.sleep(2.0)
        await self.Vehicle.Cabin.Door.Row1.Left.IsOpen.set(True)
        await asyncio.sleep(2.0)
        await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.set(1)
        await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.set(-1)
        await asyncio.sleep(2.0)
        await self.Vehicle.Cabin.Lights.AmbientLight.set(1)
        await self.Vehicle.Cabin.Lights.AmbientLight.set(2)
        await self.Vehicle.Cabin.Lights.AmbientLight.set(3)
        await self.Vehicle.Cabin.Lights.AmbientLight.set(4)
        await self.Vehicle.Cabin.Lights.AmbientLight.set(5)

        #await asyncio.sleep(2.0)
        #logger.debug(await self.Vehicle.Cabin.Seat.Row1.Pos1.Position.get())
        #await asyncio.sleep(1.0)

        pass
    async def on_speed_change(self, data: DataPointReply):
        print("on speed change")
        pass


async def main():
    """Main function"""
    logger.info("Starting SampleApp...")
    vehicle_app = SampleApp(vehicle2)
    await vehicle_app.run()

LOOP = asyncio.get_event_loop()
#LOOP.add_signal_handler(signal.SIGTERM, LOOP.stop)
LOOP.run_until_complete(main())
LOOP.close()
